import axios from 'axios'
import QS from 'qs'
import { ACCESS_TOKEN, ACCESS_SESSION } from '@/mutation-type'
import { webStorage } from '@/utils/webStorage'
import { webCookie } from '@/utils/webCookies'
import { useUserStore } from '@/store/user'
import { notification, Modal } from 'ant-design-vue'

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // api base_url
  timeout: 9000, // 请求超时时间
})

//请求拦截
service.interceptors.request.use(
  (config) => {
    // console.log('🚀 ~ file: request.js:17 ~ config:', config)
    const token = webStorage.ls.get(ACCESS_TOKEN)
    const session = webCookie.get(ACCESS_SESSION)
    if (token && !session) {
      webCookie.set(ACCESS_SESSION, token.token)
      // config.headers['X-Access-Token'] = token.token;
      // config.headers['Cookie'] = token.token
      // config.headers['Content-Type'] = 'application/json; charset=UTF-8'
      // config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    if (config.method == 'post' && config.formdata) {
      config.data = QS.stringify(config.data)
    }
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  },
)
//请求响应
service.interceptors.response.use(
  (response) => {
    return response.data
  },
  (err) => {
    if (err.response) {
      const data = err.response.data
      const token = webStorage.ls.get(ACCESS_TOKEN)
      switch (err.response.status) {
        case 401:
          notification.error({ message: '系统提示', description: '未授权，请重新登录', duration: 4 })
          if (token) {
            let user = useUserStore()
            user.logout().then((res) => {
              window.location.reload()
            })
          }
          break
        case 403:
          notification.error({ message: '系统提示', description: '拒绝访问', duration: 4 })
          break
        case 404:
          notification.error({ message: '系统提示', description: '很抱歉，资源未找到!', duration: 4 })
          break
        case 500:
          if (token && data.message.includes('Token失效')) {
            Modal.error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                let user = useUserStore()
                user.logout().then((res) => {
                  window.location.reload()
                })
              },
            })
          } else {
            message.error(data.message)
          }
          break
        case 504:
          notification.error({ message: '系统提示', description: '网关超时' })
          break
        default:
          notification.error({
            message: '系统提示',
            description: data.message,
            duration: 4,
          })
          break
      }
    }
    return Promise.reject(err)
  },
)

export { service as axios }
